import time
from loguru import logger
from DrissionPage import Chromium
from DrissionPage.errors import ElementLostError, NoRectError, ElementNotFoundError
from read_search_file import get_complete_sheet1, get_complete_sheet_platform, get_complete_sheet_indus_people, get_complete_sheet_indus_inters, get_complete_sheet_keyword, get_complete_sheet_crowd_pack
from DrissionPage.common import Keys
from create_creative import create_creative_func
import pandas as pd

'''创建单元'''

def log_message(log_callback, message, color=None):
    if callable(log_callback):
        log_callback(message, color) if color else log_callback(message)

'''创建单元主流程'''
def create_unit(u_view_tab, r_excel, browser, file_path, plan_next_button_ele=None, log_callback=None):
    # u_view_tab.wait.load_start()
    unit_name = r_excel['单元名称']
    note_id = r_excel['笔记ID']
    keywords = r_excel['关键词']
    match_type = r_excel['关键词匹配方式']
    bid_price = r_excel['关键词出价']
    age = r_excel['年龄']
    accurate_inclusion = r_excel['精准包含']

    try:
        input_unit_name_ele = u_view_tab.ele('tag:input@@class=d-text@@placeholder=请输入你的单元名称', timeout=5)
        input_unit_name_ele.input(unit_name, clear=True)
    except ElementNotFoundError:
        logger.info(f"单元名称没找到")
        if plan_next_button_ele and u_view_tab.ele('tag:input@@class=d-text@@type=text@@placeholder=请输入你的计划名称@@maxlength=50', timeout=2):
            logger.info(f"单元名称没找到, 页面还停留在创建计划页面, 重新点击下一步")
            plan_next_button_ele.click()
            u_view_tab.wait.load_start()
            input_unit_name_ele = u_view_tab.ele('tag:input@@class=d-text@@placeholder=请输入你的单元名称', timeout=2)
            input_unit_name_ele.input(unit_name, clear=True)

    # 批量添加笔记
    if u_view_tab.ele('tag:span@@class$--size-text-paragraph d-text-nowrap d-text-ellipsis d-text-nowrap@@text()= 批量添加 ', timeout=2):
        u_view_tab.ele('tag:span@@class$--size-text-paragraph d-text-nowrap d-text-ellipsis d-text-nowrap@@text()= 批量添加 ').parent(2).click(by_js=True)

        footer_container = u_view_tab.ele('tag:div@@class=d-modal-footer')
        note_id_arr = note_id.strip().split('\n')
        u_view_tab.ele('tag:input@@class=d-text@@type=text@@placeholder=回车输入多个 ID，最多 100 条').run_js('this.focus();')
        for note in note_id_arr:
            u_view_tab.actions.input(note).input(Keys.ENTER)

        u_view_tab.ele('tag:a@@class$--size-text-paragraph btn-validate@@text()=搜索').click(by_js=True)

        footer_container.ele('tag:span@@class$--size-text-paragraph d-text-nowrap d-text-ellipsis d-text-nowrap@@text()=确认添加', timeout=2).parent(2).wait.enabled()
        footer_container.ele('tag:span@@class$--size-text-paragraph d-text-nowrap d-text-ellipsis d-text-nowrap@@text()=确认添加', timeout=2).parent(2).click(by_js=True)

        # u_view_tab.ele('tag:span@@class$--size-text-paragraph d-text-nowrap d-text-ellipsis d-text-nowrap@@text()=取消', timeout=2).parent(2).click()
        u_view_tab.wait(1.5)
    else:
        note_id_arr = str(note_id).strip().split('\n')
        for i, note in enumerate(note_id_arr):
            select_note_and_choose(note, u_view_tab)
            # 二次检查笔记ID是否正确
            while True:
                u_view_tab.ele('tag:div@@text()=笔记id').wait.displayed()
                if u_view_tab.ele('tag:div@@text()=笔记id', timeout=5):
                    note_id_id = u_view_tab.ele('tag:div@@text()=笔记id').parent(3).next().child(index=i+1).child(index=2).text
                    if note_id_id == note:
                        break
                    log_message(log_callback, f'选中的笔记ID有误, 重新选择笔记ID: {i+1} 次', "red")
                    u_view_tab.ele('tag:div@@text()=笔记id').parent(3).next().child(index=i+1).ele('tag:td@@class=d-table__cell--fixed-right d-table-cell--fixed-right-first').child().run_js('this.click();') # 删掉这条笔记重新选
                    select_note_and_choose(note, u_view_tab)

    # 搜查关键词
    u_view_tab.ele('tag:span@@class$--color-text-paragraph --size-text-paragraph@@text()=搜查关键词').scroll.to_center()
    u_view_tab.ele('tag:span@@class$--color-text-paragraph --size-text-paragraph@@text()=搜查关键词').click(by_js=True)

    keyword_arr = keywords.strip().split('\n')
    u_view_tab.ele('tag:textarea@@placeholder=请输入新的关键词进行添加，多关键词可折行或用 ；间隔').scroll.to_center()
    u_view_tab.ele('tag:textarea@@placeholder=请输入新的关键词进行添加，多关键词可折行或用 ；间隔').run_js('this.focus();')
    for k in keyword_arr:
        u_view_tab.actions.input(k).input(Keys.ENTER)

    u_view_tab.ele('css:#keyword-add-table > div > div.d-table-affix-header-ele > table > thead > tr > th:nth-child(1) > div > div > div').click(by_js=True)

    ## 修改匹配方式
    u_view_tab.ele('@text()=批量修改', timeout=1).hover()
    u_view_tab.ele('@text()=统一修改匹配方式').click(by_js=True)
    u_view_tab.ele(f'tag:span@@class=d-text --color-text-title --size-text-paragraph d-text-nowrap d-text-ellipsis d-radio-label@@text()={match_type.strip()}').parent(1).click(by_js=True)
    u_view_tab.ele('tag:button@@class=d-button d-button-default d-button-with-content --color-static bold --color-bg-primary --color-white@@text()=确定').click(by_js=True)

    ## 继续修改出价
    u_view_tab.ele('@text()=批量修改', timeout=1).hover()

    u_view_tab.ele('@text()=统一修改关键词出价').click(by_js=True)
    u_view_tab.ele('tag:input@@class=d-text@@placeholder=请输入价格').input(bid_price, clear=True)
    u_view_tab.ele('tag:button@@class=d-button d-button-default d-button-with-content --color-static bold --color-bg-primary --color-white@@text()=确定').click(by_js=True)

    # 精准包含
    if match_type == '精准匹配':
        if accurate_inclusion == '关闭':
            if contain_clickable_ele := u_view_tab.ele('tag:span@@class=d-text --color-static --color-text-title --size-text-paragraph bold@@text()= 精准包含 ', timeout=2).next():
                is_checked_condition_class = contain_clickable_ele.child().attr('class')
                if 'unchecked' not in is_checked_condition_class:
                    contain_clickable_ele.click(by_js=True)
        else:
            contain_clickable_ele = u_view_tab.ele('tag:span@@class=d-text --color-static --color-text-title --size-text-paragraph bold@@text()= 精准包含 ', timeout=2).next()
            if contain_clickable_ele:
                is_checked_condition_class = contain_clickable_ele.child().attr('class')
                if 'unchecked' in is_checked_condition_class:
                    contain_clickable_ele.click(by_js=True)

    ## 智能拓词关闭
    if u_view_tab.ele('tag:span@@text()=智能拓词', timeout=1.5):
        u_view_tab.ele('tag:span@@text()=智能拓词').parent(1).next().child(1).child(2).click(by_js=True)

    u_view_tab.ele('tag:span@@text()=自定义').scroll.to_center()

    ## 地域中国
    # if '中国' == area or not area:
    is_selected_option_class_str = u_view_tab.ele('tag:span@@text()=地域').parent(1).next().child().child(index=-1).child().child().attr('class')

    if 'unchecked' in is_selected_option_class_str:
        u_view_tab.ele('tag:span@@text()=自定义').click(by_js=True)  ## 点击自定义
        u_view_tab.ele(f'tag:span@@text()=中国').scroll.to_center()
        u_view_tab.ele(f'tag:span@@text()=中国').parent(1).click(by_js=True)  ## 点击中国

    ## 年龄
    if  '不限' != age and age != '全选':
        if age_option_exists := u_view_tab.ele('css:.input div.form-container > .form-content > div.input:nth-of-type(5) > div:nth-child(1) > div > span:nth-of-type(2)', timeout=2):
            if pd.notna(age):
                age_option_exists.click(by_js=True) ## 取消年龄不限
                age_arr = age.split('\n')
                for a in age_arr:
                    if age_option := u_view_tab.ele(f'tag:span@@text()={a.strip()}', timeout=2):
                        age_option.parent(1).click(by_js=True)  ## 选中各年龄段
                    else:
                        break

    # 下一步
    unit_next_button_ele = u_view_tab.ele('tag:span@@class$--size-text-paragraph d-text-nowrap d-text-ellipsis d-text-nowrap@@text()=下一步').parent(2)
    unit_next_button_ele.scroll.to_center()
    # unit_next_button_ele.click(by_js=True)  # 点击下一步

    handle_operate_too_fast(unit_next_button_ele, u_view_tab, unit_name, log_callback)

    if u_view_tab.ele('@text():单元名称已存在', timeout=1):
        log_message(log_callback, f"单元名称:{unit_name} - 已存在", "red")
        return

    ## d-button d-button-default d-button-with-content --color-static bold --color-bg-primary --color-white
    if alert_remind_range_small_ele := u_view_tab.ele('tag:button@@class=d-button d-button-default d-button-with-content --color-static bold --color-bg-primary --color-white@@text()=继续', timeout=0.8):
        logger.info(f"创建单元界面遇到弹窗阻塞")
        log_message(log_callback, f"单元名称:{unit_name}在创建单元界面遇到弹窗阻塞", "red")
        alert_remind_range_small_ele.click(by_js=True)

    create_creative_func(u_view_tab, r_excel, browser, file_path, unit_next_button_ele, log_callback)

def select_note_and_choose(note_id, u_view_tab):
    u_view_tab.ele('tag:span@@text()=添加笔记').click(by_js=True)
    note_id_arr = note_id.strip().split('\n')
    for note in note_id_arr:
        if u_view_tab.ele('tag:input@@class=d-text@@type=text@@placeholder^请输入笔记ID', timeout=2):
            u_view_tab.ele('tag:input@@class=d-text@@type=text@@placeholder^请输入笔记ID').run_js('this.value = arguments[0]; this.dispatchEvent(new Event("input"));', note)
            u_view_tab.ele('tag:input@@class=d-text@@type=text@@placeholder^请输入笔记ID').input(Keys.ENTER)
            u_view_tab.wait(1)
        if note_choose_ele := u_view_tab.ele('tag:span@@class$--color-primary --size-text-small@@text()=选择', timeout=3):
            note_choose_ele.click(by_js=True)  ## 选择笔记
    # 点击笔记选择，点击笔记确定
    u_view_tab.ele('css:.footer-actions > .--color-bg-primary').click(by_js=True)  # 笔记确定


def handle_operate_too_fast(unit_next_button_ele, unit_view_tab, unit_name, log_callback):
    max_retries = 10  # 最大重试次数
    retry_count = 0

    while retry_count < max_retries:
        # 先检查是否已经进入下一页
        # if unit_view_tab.ele('tag:input@@class=d-text@@type=text@@placeholder=请输入你的创意名称', timeout=2):
        #     break
        unit_next_button_ele.click(by_js=True)

        if unit_view_tab.ele('@text():操作频繁', timeout=1):
            log_message(log_callback, f"创建单元页面创建单元:{unit_name} - 触发操作频繁,正在重试({retry_count + 1}/{max_retries})", "red")
            logger.info(f"操作频繁，等待后重试 ({retry_count + 1}/{max_retries})")
            time.sleep(2 * (retry_count + 1))
            # try:
            #     unit_next_button_ele.click()
            # except NoRectError:
            #     log_message(log_callback, f"单元页面没找到下一步按钮:{unit_name} - 页面已跳转，停止重试", "green")
            #     break
            retry_count += 1
        else:
            break  # 没有"操作频繁"提示时退出循环

    if retry_count == max_retries:
        log_message(log_callback, f"单元名称:{unit_name} - 已达到最大重试次数，仍然操作频繁", "red")
        logger.error("已达到最大重试次数，仍然操作频繁")
    else:
        log_message(log_callback, f"单元名称: {unit_name}-在重试({retry_count + 1}/{max_retries})次后成功执行下一步", "green")
        logger.info("操作成功执行")

# if __name__ == '__main__':
#     file_path = r"D:\Users\Desktop\搜索-创建计划-样例（5月计划.xlsx"
#
#     browser = Chromium()  ## 临时测试、到时候删掉， 只保留调用create_unit()函数
#     unit_view_tab = browser.latest_tab  ## 临时测试、到时候删掉
#     unit_view_tab.get('https://ad.xiaohongshu.com/aurora/ad/create/unit/119720230/4/2?isStep=true&AFormGrayFlag=false&vSellerId=63be38f04ee9db000147041b')  ## 临时测试、到时候删掉')  ## 临时测试、到时候删掉
#
#     sheet1_data = get_complete_sheet1(file_path)
#     for index, row in sheet1_data.iterrows():
#         if index == 0:
#             create_unit(unit_view_tab, row, browser, file_path)



